import { expect } from '@jest/globals';
import * as compressing from 'compressing';
import fs from 'fs-extra';
import fsExtra from 'fs-extra';
import path from 'path';

import { initExecuteCommand, runHvigorAsync } from '../../common/common';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  IsEnable,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
  SignType
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOption } from '../../plugins/task-builder/test-task-option';


const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API10,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility,
  }
};

const taskConfig: TestTaskOption = {
  caseLevel: CaseLevel.L1,
  sign: SignType.Sign,
  ohpmInstall: IsEnable.DisAble,
};

const testFun: TestCaseFun = async (project, taskConfig, record) => {
  const projectRootPath = project.projectRootPath();
  const command = initExecuteCommand({
    mode: 'module',
    tasks: 'assembleHap',
    product: 'default',
    debuggable: 'false',
    buildMode: 'release'
  });
  const result = await runHvigorAsync(projectRootPath, command);
  record.addStep('执行 ./hvigorw assembleHap -p debuggable=false', result);
  expect(result.stdout).toContain('Finished :entry:assembleHap');
  expect(result.stdout).toContain('BUILD SUCCESSFUL');

  // 解压 hap
  await fsExtra.copyFile(
    path.resolve(project.getModule('entry').moduleRootPath(), 'build/default/outputs/default/entry-default-signed.hap'),
    // eslint-disable-next-line max-len
    path.resolve(project.getModule('entry').moduleRootPath(), 'build/default/outputs/default/entry-default-signed.zip'));
  const dirPath = path.resolve(
    project.getModule('entry').moduleRootPath(), 'build/default/outputs/default/entry-default-signed');
  await compressing.zip.uncompress(
    path.resolve(project.getModule('entry').moduleRootPath(), 'build/default/outputs/default/entry-default-signed.zip')
    , dirPath);

  // 读取目录下的所有文件
  const files = await fs.readdir(dirPath);

  // 过滤掉 .js 和 .map 文件
  const filtered = files.filter(file => {
    // 获取文件的扩展名
    const ext = path.extname(file);

    // 判断是否是 .js 或 .map
    return ext === '.js' || ext === '.map';
  });

  expect(filtered.length === 0).toBe(true);

};

TestCaseBuilder.builder()
  .caseName('OPEN_LAB_AIDE_ZOS_module_buildHap_HOS_API10_STAGE_009')
  .description('Stage模型ets工程，ets+cpp共享模块打包')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(taskConfig)
  .testFun(testFun)
  .load();
